package com.code.test.ali;

import java.util.Stack;

/**
 * https://leetcode.cn/problems/implement-queue-using-stacks/description/
 * 用栈实现队列
 */
public class QueueWithStack {

    Stack<Integer> stackIn;
    Stack<Integer> stackOut;

    /** Initialize your data structure here. */
    public QueueWithStack() {
        stackIn = new Stack<>(); // 负责进栈
        stackOut = new Stack<>(); // 负责出栈
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        stackIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        dumpstackIn();
        return stackOut.pop();
    }

    /** Get the front element. */
    public int peek() {
        dumpstackIn();
        return stackOut.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }

    // 如果stackOut为空，那么将stackIn中的元素全部放到stackOut中
    private void dumpstackIn(){
        if (!stackOut.isEmpty()) return;
        while (!stackIn.isEmpty()){
            stackOut.push(stackIn.pop());
        }
    }
}


//class MyQueue {
//    Stack<Integer> in;
//    Stack<Integer> out;
//
//    public MyQueue() {
//        in = new Stack();
//        out = new Stack();
//    }
//
//    public void push(int x) {
//        in.push(x);
//    }
//
//    public int pop() {
//        transfer();
//        return out.pop();
//    }
//
//    private void transfer() {
//        if (out.isEmpty()) {
//            while (!in.isEmpty()) {
//                out.push(in.pop());
//            }
//        }
//    }
//
//    public int peek() {
//        transfer();
//        return out.peek();
//    }
//
//    public boolean empty() {
//        return in.isEmpty() && out.isEmpty();
//    }
//}
